﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ParsecParser;
using ParsecClient.Classes;
using System.Configuration;

namespace ParsecClient
{
    /// <summary>
    /// Interaction logic for Settings.xaml
    /// </summary>
    public partial class SettingsWindow : Window
    {
        private bool IsDragging = false;
        private Dictionary<string, CharacterSettings> CharacterSettingChanges = new Dictionary<string, CharacterSettings>();
        private DateTime LastTimeServerConnect = new DateTime();
        private enum CharacterClassType
        {
            KnightJugg = 1,
            SageSorc = 0
        }
        public SettingsWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                CharacterSettingChanges = new Dictionary<string, CharacterSettings>();
                txtLogLocation.Text = ((ParsecWindow)Owner).LogFolderPath;
                sldOpacity.Value = Owner.Opacity * 100;
                chkAlwaysOnTop.IsChecked = Owner.Topmost;
                chkStreamMode.IsChecked = ((App)Application.Current).IsStreamMode;
                chkDisableHwAccel.IsChecked = ((App)Application.Current).IsSoftwareRenderingMode;
                IsDragging = true;
                sldVolume.Value = ((App)Application.Current).VolumeSetting;
                IsDragging = false;
                BindTimeServerForm();
                bool isTimeSyncEnabled = chkTimeServerSyncEnabled.IsChecked ?? false;
                bool isTimeSyncDefault = chkTimeServerUseDefault.IsChecked ?? false;
                SetTimeServerForm(isTimeSyncEnabled, isTimeSyncDefault);

                if (((ParsecWindow)Owner).Log != null && !string.IsNullOrEmpty(((ParsecWindow)Owner).Log.CharacterName))
                    ((App)Application.Current).SaveCharacterSettings(((ParsecWindow)Owner).Log.CharacterName);

                var chars = ((App)Application.Current).AllCharacterSettings.ToList().Select(x => x.CharacterName).OrderBy(x => x).ToList();
                ddlCharacters.ItemsSource = chars;
                ParsecWindow mw = ((ParsecWindow)Owner);
                string currentChar = chars.FirstOrDefault();
                if (mw != null && mw.Log != null && !string.IsNullOrEmpty(mw.Log.CharacterName))
                {
                    currentChar = mw.Log.CharacterName;
                }
                if (!string.IsNullOrEmpty(currentChar))
                {
                    ddlCharacters.SelectionChanged -= new SelectionChangedEventHandler(ddlCharacters_SelectionChanged);
                    ddlCharacters.SelectedValue = currentChar;
                    ddlCharacters.SelectionChanged += new SelectionChangedEventHandler(ddlCharacters_SelectionChanged);
                    var c = ((App)Application.Current).AllCharacterSettings.FirstOrDefault(x => x.CharacterName == currentChar);
                    if (c != null)
                    {
                        txtShieldValue.Text = c.AbsorbShieldValue.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Loading Settings", "Error on Window_Loaded", ex, this, true);
            }
        }
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //save changes
                if (!System.IO.Directory.Exists(txtLogLocation.Text))
                    ((App)Application.Current).HandleError("Folder does not exist", null, null, this, false);
                else
                {
                    //validate time settings
                    bool isTimeSyncEnabled = chkTimeServerSyncEnabled.IsChecked ?? false;
                    bool isTimeServerDefault = chkTimeServerUseDefault.IsChecked ?? false;
                    int timeServerPort = 0;
                    string timeServerHostName = string.Empty;
                    if (!isTimeServerDefault)
                    {
                        int newPort = 0;
                        if (!int.TryParse(txtTimeServerPort.Text ?? "", out newPort))
                        {
                            ((App)Application.Current).HandleError("Invalid Time Server Port", null, null, this, false);
                            return;
                        }
                        if (string.IsNullOrEmpty(txtTimeServerHost.Text))
                        {
                            ((App)Application.Current).HandleError("Time Server Host Name is required", null, null, this, false);
                            return;
                        }
                        timeServerPort = newPort;
                        timeServerHostName = txtTimeServerHost.Text;
                    }
                    bool timeServerDirty = (((App)Application.Current).TimeSyncEnabled != isTimeSyncEnabled)
                        || (((App)Application.Current).TimeServerDefault != isTimeServerDefault)
                        || (((App)Application.Current).TimeServerHostNameSetting != timeServerHostName)
                        || (((App)Application.Current).TimeServerPortSetting != timeServerPort);
                    if (timeServerDirty)
                    {
                        ((App)Application.Current).TimeSyncEnabled = isTimeSyncEnabled;
                        ((App)Application.Current).TimeServerDefault = isTimeServerDefault;
                        ((App)Application.Current).TimeServerHostNameSetting = timeServerHostName;
                        ((App)Application.Current).TimeServerPortSetting = timeServerPort;
                        ((App)Application.Current).RestartTimeSync();
                        ((App)Application.Current).UpdateTimeSync(true);
                    }

                    ParsecWindow mw = ((ParsecWindow)Owner);
                    mw.LogFolderPath = txtLogLocation.Text;
                    mw.Topmost = chkAlwaysOnTop.IsChecked.HasValue ? chkAlwaysOnTop.IsChecked.Value : false;
                    ((App)Application.Current).IsSoftwareRenderingMode = chkDisableHwAccel.IsChecked.HasValue ? chkDisableHwAccel.IsChecked.Value : false;
                    ((App)Application.Current).IsStreamMode = chkStreamMode.IsChecked.HasValue ? chkStreamMode.IsChecked.Value : false;
                    ((App)Application.Current).SaveSettings();

                    ((App)Application.Current).LoadWindowSettings();

                    if (CharacterSettingChanges.Count > 0)
                    {
                        var chars = new List<string>(CharacterSettingChanges.Keys);
                        foreach (string c in chars)
                        {
                            if (!string.IsNullOrEmpty(c))
                            {
                                var unsavedSettings = CharacterSettingChanges[c];
                                var csettings = ((App)Application.Current).AllCharacterSettings.FirstOrDefault(x => x.CharacterName == c);
                                if (csettings != null)
                                {
                                    csettings.AbsorbShieldValue = unsavedSettings.AbsorbShieldValue;
                                    ((App)Application.Current).AllCharacterSettings = CharacterSettingsCollection.SaveCharacterSettings(csettings);
                                }
                            }
                        }
                    }

                    if (((ParsecWindow)Owner).Log != null && !string.IsNullOrEmpty(((ParsecWindow)Owner).Log.CharacterName))
                        ((App)Application.Current).ApplyCharacterSettings(((ParsecWindow)Owner).Log.CharacterName);

                    this.Close();
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Saving Settings", "Error on btnOk_Click", ex, this, true);
                this.Close();
            }
        }
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            //undo changes
            try
            {
                ((App)Application.Current).LoadWindowSettings();
                if (((ParsecWindow)Owner).Log != null && !string.IsNullOrEmpty(((ParsecWindow)Owner).Log.CharacterName))
                    ((App)Application.Current).ApplyCharacterSettings(((ParsecWindow)Owner).Log.CharacterName);
                this.Close();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Canceling Settings", "Error on btnCancel_Click", ex, this, true);
                this.Close();
            }
        }
        private void btnRestore_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ParsecWindow mw = ((ParsecWindow)Owner);
                ((App)Application.Current).ResetSettings(false, false);
                if (((ParsecWindow)Owner).Log != null && !string.IsNullOrEmpty(((ParsecWindow)Owner).Log.CharacterName))
                {
                    ((App)Application.Current).ApplyCharacterSettings(((ParsecWindow)Owner).Log.CharacterName);
                    ((App)Application.Current).SaveCharacterSettings(((ParsecWindow)Owner).Log.CharacterName);
                }
                txtLogLocation.Text = mw.LogFolderPath;
                sldOpacity.Value = mw.Opacity * 100;
                chkAlwaysOnTop.IsChecked = mw.Topmost;
                IsDragging = true;
                sldVolume.Value = ((App)Application.Current).VolumeSetting;
                IsDragging = false;
                this.Close();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Restoring Default Settings", "Error on btnRestore_Click", ex, this, true);
            }
        }

        private void btnFolder_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog())
                {
                    dlg.ShowNewFolderButton = false;
                    if (System.IO.Directory.Exists(txtLogLocation.Text))
                        dlg.SelectedPath = txtLogLocation.Text;

                    System.Windows.Forms.DialogResult result = dlg.ShowDialog();
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        txtLogLocation.Text = dlg.SelectedPath;
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Loading Folder Dialog", "Error on Folder Dialog button click", ex, this, true);
            }
        }
        private void sldOpacity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            try
            {
                if (Owner != null)
                {
                    Owner.Opacity = sldOpacity.Value / 100d;
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Changing Opacity", "Error on sldOpacity_ValueChanged", ex, this, true);
            }
        }
        private void sldVolume_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
        {
            IsDragging = true;
        }
        private void sldVolume_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            IsDragging = false;
            sldVolume_ValueChanged(sender, null);
        }
        private void sldVolume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            try
            {
                if (!IsDragging)
                {
                    if (Owner != null)
                    {
                        //set volume setting
                        ((App)Application.Current).VolumeSetting = Convert.ToInt32(sldVolume.Value);
                        System.Audio.Volume = ((App)Application.Current).VolumeSetting;
                        ParsecClientHelpers.PlaySound(TimerSound.ItsATrap);
                        //set volume
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Changing Volume", "Error on sldVolume_ValueChanged", ex, this, true);
            }
        }
        private void txtShieldValue_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                string currentChar = (string)ddlCharacters.SelectedValue;
                if (!string.IsNullOrEmpty(currentChar))
                {
                    double shieldValue = 0;
                    string tempVal = txtShieldValue.Text;
                    if (!string.IsNullOrEmpty(tempVal))
                        double.TryParse(tempVal, out shieldValue);
                    if (shieldValue < 0 || shieldValue > 15000)
                    {
                        txtShieldValue.Text = "0";
                        ((App)Application.Current).HandleError(string.Format("Shield Value must be between 0 and {0}",(15000).ToString("N")), null, null, this, false);
                    }
                    else
                    {
                        CharacterSettings unsavedSettings;
                        if (CharacterSettingChanges.TryGetValue(currentChar, out unsavedSettings))
                        {
                            unsavedSettings.AbsorbShieldValue = shieldValue;
                        }
                        else
                        {
                            CharacterSettingChanges.Add(currentChar, new CharacterSettings() { CharacterName = currentChar, AbsorbShieldValue = shieldValue });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Changing Shield Value", "Error on txtShieldValue_TextChanged", ex, this, true);
            }
        }
        private void btnUseCalc_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string v = txtCalcTotal.Text;
                double d;
                if (!string.IsNullOrEmpty(v) && double.TryParse(v, out d))
                {
                    txtShieldValue.Text = v.ToString();
                }
                grdShieldValue.Visibility = System.Windows.Visibility.Visible;
                boxCalculator.Visibility = System.Windows.Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnUseCalc_Click", ex, this, true);
            }
        }
        private void txtBonusHeals_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                double b = 0;
                string bh = !string.IsNullOrEmpty(txtBonusHeals.Text) ? txtBonusHeals.Text : "0";
                double.TryParse(bh, out b);
                CharacterClassType c = rdoSage.IsChecked ?? false ? CharacterClassType.SageSorc : CharacterClassType.KnightJugg;
                txtCalcTotal.Text = GetShieldValue(b, chkAddTenPct.IsChecked ?? false, c).ToString();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on txtBonusHeals_TextChanged", ex, this, true);
            }
        }
        private void chkAddTenPct_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtBonusHeals != null && txtCalcTotal != null)
                {
                    double b = 0;
                    string bh = !string.IsNullOrEmpty(txtBonusHeals.Text) ? txtBonusHeals.Text : "0";
                    double.TryParse(bh, out b);
                    CharacterClassType c = rdoSage.IsChecked ?? false ? CharacterClassType.SageSorc : CharacterClassType.KnightJugg;
                    txtCalcTotal.Text = GetShieldValue(b, chkAddTenPct.IsChecked ?? false, c).ToString();
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on chkAddTenPct_Checked", ex, this, true);
            }
        }
        private void chkAddTenPct_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtBonusHeals != null && txtCalcTotal != null)
                {
                    double b = 0;
                    string bh = !string.IsNullOrEmpty(txtBonusHeals.Text) ? txtBonusHeals.Text : "0";
                    double.TryParse(bh, out b);
                    CharacterClassType c = rdoSage.IsChecked ?? false ? CharacterClassType.SageSorc : CharacterClassType.KnightJugg;
                    txtCalcTotal.Text = GetShieldValue(b, chkAddTenPct.IsChecked ?? false, c).ToString();
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on chkAddTenPct_Unchecked", ex, this, true);
            }
        }
        private void btnCalc_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                grdShieldValue.Visibility = System.Windows.Visibility.Collapsed;
                boxCalculator.Visibility = System.Windows.Visibility.Visible;
                chkAddTenPct.IsChecked = true;
                txtBonusHeals.Text = "0";
                rdoSage.IsChecked = true;
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnCalc_Click", ex, this, true);
            }
        }
        private void btnCancelCalc_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                grdShieldValue.Visibility = System.Windows.Visibility.Visible;
                boxCalculator.Visibility = System.Windows.Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnCancelCalc_Click", ex, this, true);
            }
        }
        private void ddlCharacters_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                string currentChar = (string)ddlCharacters.SelectedValue;
                if (!string.IsNullOrEmpty(currentChar))
                {
                    CharacterSettings unsavedValue;
                    if (CharacterSettingChanges.TryGetValue(currentChar, out unsavedValue))
                    {
                        txtShieldValue.Text = unsavedValue.AbsorbShieldValue.ToString();
                    }
                    else
                    {
                        var c = ((App)Application.Current).AllCharacterSettings.FirstOrDefault(x => x.CharacterName == currentChar);
                        if (c != null)
                        {
                            txtShieldValue.Text = c.AbsorbShieldValue.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Loading Fight", "Error on ddlCharacters_SelectionChanged", ex, this, true);
            }

        }
        private void ShieldCalcCheckedHandler(object sender, RoutedEventArgs e)
        {
            if (rdoSage.IsChecked ?? false)
            {
                lblPctBonus.Content = "10% Talent";
                lblPctBonus.Visibility = System.Windows.Visibility.Visible;
                chkAddTenPct.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                lblPctBonus.Content = "20% Set bonus";
                lblPctBonus.Visibility = System.Windows.Visibility.Hidden;
                chkAddTenPct.Visibility = System.Windows.Visibility.Hidden;
            }
            double b = 0;
            string bh = !string.IsNullOrEmpty(txtBonusHeals.Text) ? txtBonusHeals.Text : "0";
            double.TryParse(bh, out b);
            CharacterClassType c = rdoSage.IsChecked ?? false ? CharacterClassType.SageSorc : CharacterClassType.KnightJugg;
            txtCalcTotal.Text = GetShieldValue(b, chkAddTenPct.IsChecked ?? false, c).ToString();

        }
        private void chkTimeServerSyncEnabled_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                bool isTimeSyncEnabled = chkTimeServerSyncEnabled.IsChecked ?? false;
                bool isTimeServerDefault = chkTimeServerUseDefault.IsChecked ?? false;
                SetTimeServerForm(isTimeSyncEnabled, isTimeServerDefault);
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on chkTimeServerSyncEnabled_Checked", ex, this, true);
            }
        }
        private void chkTimeServerUseDefault_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                bool isTimeSyncEnabled = chkTimeServerSyncEnabled.IsChecked ?? false;
                bool isTimeServerDefault = chkTimeServerUseDefault.IsChecked ?? false;
                SetTimeServerForm(isTimeSyncEnabled, isTimeServerDefault);
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on chkTimeServerUseDefault_Checked", ex, this, true);
            }
        }
        private void btnTestTimeServer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //test sync
                bool isTimeSyncEnabled = chkTimeServerSyncEnabled.IsChecked ?? false;
                bool isTimeServerDefault = chkTimeServerUseDefault.IsChecked ?? false;
                if (isTimeSyncEnabled)
                {
                    if (LastTimeServerConnect.AddSeconds(5) > DateTime.Now)
                    {
                        ((App)Application.Current).HandleError("You must wait 5 seconds after a successful test or refresh", null, null, this, false);
                    }
                    else
                    {
                        string responseText = null;
                        string timeServerHostName = ((App)Application.Current).DefaultTimeServer;
                        int timeServerPort = 123;
                        if (!isTimeServerDefault)
                        {
                            int newPort = 0;
                            if (!int.TryParse(txtTimeServerPort.Text ?? "", out newPort))
                            {
                                ((App)Application.Current).HandleError("Invalid Port", null, null, this, false);
                                return;
                            }
                            if (string.IsNullOrEmpty(txtTimeServerHost.Text))
                            {
                                ((App)Application.Current).HandleError("Time Server Host Name is required", null, null, this, false);
                                return;
                            }
                            timeServerPort = newPort;
                            timeServerHostName = txtTimeServerHost.Text;
                        }

                        var s = new SNTPClient(timeServerHostName, timeServerPort);
                        try
                        {
                            s.Connect();
                            LastTimeServerConnect = DateTime.Now;
                        }
                        catch (Exception ex)
                        {
                            responseText = string.Format("Test Failed: {0}", ex.Message);
                            ((App)Application.Current).HandleError(null, "Error Testing Time Server Connection", ex, null, true);
                        }
                        if (responseText == null)
                            responseText = string.Format("Success! {2}:{3} Status: {0} Offset: {1}", s.IsResponseValid() ? "OK" : "OFFLINE", s.LocalClockOffset.ToString(), timeServerHostName, timeServerPort.ToString());
                        ((App)Application.Current).HandleMessage(responseText, this);
                        s = null;
                    }

                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnTestTimeServer_Click", ex, this, true);
            }
        }
        private void btnRefreshSync_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (LastTimeServerConnect.AddSeconds(5) > DateTime.Now)
                {
                    ((App)Application.Current).HandleError("You must wait 5 seconds after a successful test or refresh", null, null, this, false);
                }
                else
                {
                    ((App)Application.Current).RestartTimeSync();
                    ((App)Application.Current).UpdateTimeSync(true);
                    if (((App)Application.Current).TimeSyncEnabled && !((App)Application.Current).IsTimeServerRunning())
                    {
                        try
                        {
                            //attempt to correct time service problem
                            using (var controller = new System.ServiceProcess.ServiceController("w32time"))
                            {
                                if (controller != null && controller.Status != System.ServiceProcess.ServiceControllerStatus.Stopped)
                                {
                                    //controller.Stop();
                                    if (((App)Application.Current).HandleAskMessage("Parsec has detected that the Windows Time Service has locked the Time Server port. Would you like to stop this service? \r\n\r\nWindows will automatically restart this service when it is scheduled to sync your clock", this))
                                    {
                                        var p = new System.Diagnostics.ProcessStartInfo();
                                        p.UseShellExecute = true;
                                        p.CreateNoWindow = false;
                                        p.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System);
                                        p.FileName = "cmd.exe";
                                        p.Arguments = @"/c net stop w32time";
                                        p.Verb = "runas";
                                        System.Diagnostics.Process.Start(p);
                                        try
                                        {
                                            controller.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new System.TimeSpan(0, 0, 0, 10, 0));
                                        }
                                        catch (System.ServiceProcess.TimeoutException ex)
                                        {
                                            ((App)Application.Current).HandleError(string.Format("Parsec was unable to verify that the service was stopped"), "Service Stop Timeout Exceeded", ex, null, false);
                                        }
                                        ((App)Application.Current).RestartTimeSync();
                                        ((App)Application.Current).UpdateTimeSync(true);
                                    }
                                }
                                if (controller != null)
                                    controller.Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.WriteError("Unknown Error attempting to fix Time Service Problem", ex);
                        }
                    }
                    if (((App)Application.Current).IsTimeServerRunning())
                        LastTimeServerConnect = DateTime.Now;
                    txtTimeServerStatus.Text = ((App)Application.Current).GetTimeServerStatus();
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnRefreshSync_Click", ex, this, true);
            }
        }

        private double GetShieldValue(double bonusHeal, bool useSkillMod, CharacterClassType c)
        {
            double value = 0.0;
            double modifier = 1.0;
            if (c == CharacterClassType.SageSorc)
            {
                //value = 1834 + (3.27 * bonusHeal);
                value = 2178 + (3 * bonusHeal);
                modifier = 1.1;
            }
            else if (c == CharacterClassType.KnightJugg)
            {
                //value = 0.05 * 11180 + bonusHeal;
                //modifier = 1.2;
                value = 726 + bonusHeal;
            }
            if (!useSkillMod)
                modifier = 1.0;
            return value * modifier;
        }
        private void SetTimeServerForm(bool isTimeSyncEnabled, bool isTimeServerDefault)
        {
            lblTimeServerUseDefault.IsEnabled = isTimeSyncEnabled;
            chkTimeServerUseDefault.IsEnabled = isTimeSyncEnabled;
            lblTimeServerHost.IsEnabled = isTimeSyncEnabled && !isTimeServerDefault;
            txtTimeServerHost.IsEnabled = isTimeSyncEnabled && !isTimeServerDefault;
            lblTimeServerPort.IsEnabled = isTimeSyncEnabled && !isTimeServerDefault;
            txtTimeServerPort.IsEnabled = isTimeSyncEnabled && !isTimeServerDefault;
            btnTestTimeServer.IsEnabled = isTimeSyncEnabled;
        }
        private void BindTimeServerForm()
        {
            txtTimeServerStatus.Text = ((App)Application.Current).GetTimeServerStatus();
            bool isTimeSyncEnabled = ((App)Application.Current).TimeSyncEnabled;
            bool isTimeServerDefault = ((App)Application.Current).TimeServerDefault;
            chkTimeServerSyncEnabled.IsChecked = isTimeSyncEnabled;
            chkTimeServerUseDefault.IsChecked = isTimeServerDefault;
            if (isTimeServerDefault)
            {
                txtTimeServerHost.Text = ((App)Application.Current).DefaultTimeServer;
                txtTimeServerPort.Text = "123";
            }
            else
            {
                txtTimeServerHost.Text = ((App)Application.Current).TimeServerHostNameSetting;
                txtTimeServerPort.Text = ((App)Application.Current).TimeServerPortSetting.ToString();
            }
        }

        private void btnResetCharacter_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string currentChar = (string)ddlCharacters.SelectedValue;
                if (!string.IsNullOrEmpty(currentChar))
                {
                    txtShieldValue.Text = "0";
                    if (CharacterSettingChanges.ContainsKey(currentChar))
                    {
                        CharacterSettingChanges.Remove(currentChar);
                        var csettings = ((App)Application.Current).AllCharacterSettings.FirstOrDefault(x => x.CharacterName == currentChar);
                        if (csettings != null)
                        {
                            csettings = new CharacterSettings() { CharacterName = currentChar };
                            ((App)Application.Current).AllCharacterSettings = CharacterSettingsCollection.SaveCharacterSettings(csettings);
                            if (((ParsecWindow)Owner).Log != null && !string.IsNullOrEmpty(((ParsecWindow)Owner).Log.CharacterName) && ((ParsecWindow)Owner).Log.CharacterName == currentChar)
                                ((App)Application.Current).ApplyCharacterSettings(((ParsecWindow)Owner).Log.CharacterName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnResetCharacter_Click", ex, this, true);
            }
        }

    }
}
